<template>
  <div :class="`tw-libformlist x${_uid} ` + config.custClass">
    <generate-form
      @on-change="handleDataChange"
      :list="datalist"
      :config="config"
      :value="widgetModels"
      ref="generateForm">
    </generate-form>
  </div>
</template>

<script>
import props from './props'
import GenerateForm from './GenerateForm'
import VueEditor from 'vue2-editor'

export default {
  name: 'libinput',

  provide () {
    return {
      _root: this
    }
  },

  components: {
    VueEditor,
    GenerateForm
  },

  props,

  data() {
    return {
      val: '',
      datalist: [],
      widgetModels: {},
      loading: false
    }
  },

  methods: {
    handleDataChange (field, value, data) {
      // console.log(field, value)
      // console.log(value)
      // this.widgetModels = data
      let isdiff = this.diffObject(this.widgetModels, data)
      if (!isdiff) {
        // console.log('data', data)
        if (!this.config.submitBtn) {
          this.$emit('input', data)
          this.$emit('change', data)
        }
      } else {
        // console.log('widgetModels', this.widgetModels)
        // console.log('widgetModelsdata', data)
      }
      // console.log('widgetModels', this.widgetModels)

    },

    validFunc (val) {
      if (this.custValidFunc !== '' && typeof this.custValidFunc === 'function') {
        return  this.custValidFunc(rule, value, callback, val)
      } else {
        return (rule, value, callback) => {
          if (value === '') {
            callback(new Error('输入值不能为空'))
          } else {
            callback()
          }
        }
      }
    },
    getAutoAddValue (model, index, options, models) {
      let rdata
      if (this.autoAddFunc !== '' && typeof this.autoAddFunc === 'function') {
        rdata = this.autoAddFunc(model, index, options, models)
      } else {
        if (options.type === 'text') {
          let i = 65
          rdata = String.fromCharCode(i + index) + ' 卷'
        } else if (options.type === 'date' && options.options.type === 'daterange') {
          let premodel = model
          if (index > 1) {
            premodel = premodel + (index - 1)
          }
          let prevalue = models[index - 1][premodel]
          rdata = []
          if (prevalue && prevalue instanceof Array && prevalue.length > 1) {
            rdata = [prevalue[1], prevalue[1]]
          }
        }
      }
      return rdata
    },
    setStyle () {
      let style = `
        .tw-libformlist.x${this._uid}  {
        }
      `

      if (this.setCusStyle !== '' && typeof this.setCusStyle === 'function') {
        style += this.setCusStyle()
      }

      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/\n/g, '')

      document.head.appendChild(styleEl)
    },

    // 初始化数据，将value转化为动态创建的表单部分
    init () {
      this.datalist = JSON.parse(JSON.stringify(this.list))

      this.list.forEach((item, index) => {
        if (item.type === 'grid' && item.childType === 'dymFrom' && this.value) {
          if (this.value[item.model] && this.value[item.model].length > 1 && item.mulforms.length < this.value[item.model].length) {
            let data = this.datalist[index].mulforms[0].list
            // console.log('value', this.value)
            for (let i = 1; i < this.value[item.model].length; i++) {
              let list = []
              for (let j = 0; j < data.length; j++) {
                list.push({
                  ...data[j],
                  key: data[j].key + i,
                  model: data[j].model + i
                })
              }
              this.datalist[index].mulforms.push({list: list})
            }
          }
        }
      })
      // console.log('this.datalist', this.datalist)
    },
    diffObject(object, other) {
      let diff = true

      let objlength = Object.keys(object).length
      let othlength = Object.keys(other).length
      if (objlength !== othlength) {
        diff = false
        return diff
      }
      for (let key in object) {
        if (object[key] instanceof Array && other[key] instanceof Array) {
          diff = this.diffArray(object[key], other[key])
          if (!diff) {
            return diff
          }
        } else if (typeof object[key] === 'object' && typeof other[key] === 'object' && object[key] && other[key]) {

          diff = this.diffObject(object[key], other[key])
          if (!diff) {
            return diff
          }
        } else if (object[key] !== other[key]) {
          diff = false
          return diff
        } else {
          diff = true
        }
      }

      return diff
    },
    diffArray (arr, other) {
      let diff = true
      // return false
      if (arr.length !== other.length) {
        diff = false
        return diff
      } else {
        arr.forEach((item, index) => {
          if (item instanceof Array && other[index] instanceof Array) {
            diff = this.diffArray(item, other[index])
            if (!diff) {
              return diff
            }
          } else if (item && other[index] && typeof item === 'object' && typeof other[index] === 'object') {
            diff = this.diffObject(item, other[index])
            if (!diff) {
              return diff
            }
          } else if (item !== other[index]) {
            diff = false
            return diff
          } else {
            diff = true
          }
        })
      }

      return diff
    }
  },

  computed: {
    config () {
      return {
        custClass: this.custClass,
        labelWidth: parseInt(this.labelWidth),
        labelPosition: this.labelPosition,
        action: this.action,
        withcredentials: this.withcredentials,
        size: this.size,
        submitBtn: this.submitBtn,
        icons: this.icons
      }
    },
    style () {
      return {
        color: this.color,
        bgColor: this.bgColor,
        borderColor: this.borderColor,
        focusBorderColor: this.focusBorderColor
      }
    }
  },

  mounted () {
    this.setStyle()

    this.widgetModels = this.value
    this.init()
  },

  watch: {
    value: {
      deep: true,
      handler (val) {
        let isdiff = this.diffObject(this.widgetModels, val)
        if (!isdiff) {
          this.widgetModels = this.value
          this.init()
        }
      }
    },
    list: {
      deep: true,
      handler () {
        this.init()
      }
    },

    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
